<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="100px" v-formkey="{query:toQuery}">
          <el-row :gutter="10">
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="业务日期">
                    <div class="flex flex-row">
                      <el-date-picker
                        v-model="query.startTime"
                        align="right"
                        unlink-panels
                        class="fl1"
                        format="yyyy - MM - dd "
                        value-format="yyyy-MM-dd"
                        default-value
                        range-separator=""
                        placeholder="开始日期"
                      />
                      <el-date-picker
                        v-model="query.endTime"
                        align="right"
                        unlink-panels
                        class="fl1"
                        format="yyyy - MM - dd "
                        value-format="yyyy-MM-dd"
                        default-value
                        range-separator=""
                        placeholder="结束日期"
                      />
                    </div>
                  </el-form-item>
                </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="生效开始日期" prop="cutOffDate">
                  <el-date-picker
                    v-model="query.effectStartTime" style="width: 100%"
                    type="date"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"/>
                </el-form-item>
                </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-form-item label="生效结束日期" prop="cutOffDate">
                  <el-date-picker
                    v-model="query.effectEndTime" style="width: 100%"
                    type="date"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    placeholder="选择日期"/>
                </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="赠品状态">
                    <el-select
                      v-model="query.status"
                      class="filter-item"
                      clearable
                      placeholder="赠品状态"
                      size="small"
                      style="width: 100%"
                      @change="crud.toQuery"
                    >
                      <el-option
                        v-for="item in dict.common_status"
                        :key="item.id"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
            <el-col :xs="24" :sm="8" :md="6" :lg="6" :xl="6">
              <el-form-item label="部门">
                <TreeSelect
                  v-model="query.deptIds"
                  :options="deptList"
                  placeholder="部门"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'deptList','deptIds')"
                />
              </el-form-item>
            </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                  <el-form-item label="客户名称">
                    <el-input  v-model="query.customerName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户编码">
                <el-input  v-model="query.customerCode"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="商品类型">
                  <zSelect multiple  :value.sync="query.goodsTagIds" :showName="query.goodsTagName"  url="api/dropDown/basGoodsTagList"    style="width: 100%;"/>
<!--                <el-select-->
<!--                  v-model="query.giftType"-->
<!--                  class="filter-item"-->
<!--                  clearable-->
<!--                  placeholder="赠品类型"-->
<!--                  size="small"-->
<!--                  style="width: 100%"-->
<!--                  @change="crud.toQuery"-->
<!--                >-->
<!--                  <el-option-->
<!--                    v-for="item in dict.t_sales_gift_list_gift_type"-->
<!--                    :key="item.id"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value"-->
<!--                  />-->
<!--                </el-select>-->
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属商贸公司" >
              <zSelect :value.sync="query.fCustomerIds" v-if="isShow" v-model="query.fCustomerIds"   multiple url="api/dropDown/basCustomerList" :params="{type:2}"
                       style="width: 100%"/>
            </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col  :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="是否过滤零库存" label-width="100px">
                <el-select v-model="query.isIgnoreZeroUnGiftGoodsCount" class="edit-input" placeholder="请选择"         style="width:  100%">
                  <el-option
                    v-for="(item,index) in dict.common_yes_or_no"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属二批"  >
              <zSelect :value.sync="query.sCustomerIds" v-if="isShow"  v-model="query.sCustomerIds" multiple  url="api/dropDown/basCustomerList" :params="{type:3}"
                       style="width: 100%"/>
            </el-form-item>
            </el-col>
<!--            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">-->
<!--              <el-form-item label="商品名称">-->
<!--                <el-input  v-model="query.goodsName"></el-input>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="商品">
                <table-select
                  :tableColumns="[{prop:'goodsCode',label:'商品编码',width:'100'},{prop:'goodsName',label:'商品名称',width: '280'}]"
                  labelKey="goodsName"
                  valueKey="goodsId"
                  :value.sync="query.goodsIds"
                  placeholder="请选择商品"
                  url="/api/dropDown/basGoodsListForAdd"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="备注">
              <el-input  v-model="query.remark"></el-input>
            </el-form-item>
            </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6"  align="center" style="margin-top: 5px">
                <el-button class="filter-item"  size="mini" type="primary" @click="crud.toQuery">搜索</el-button>
                <el-button class="filter-item" plain   size="mini" type="primary"
                           @click="resetQuery">重置</el-button>
<!--                <rrOperation :crud="crud"/>-->
              </el-col>

          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="success"
          @click="crud.enableOrDisable('ENABLE')"
        >启用</el-button>
        <el-button
          slot="left"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="danger"
          @click="crud.enableOrDisable('DISABLE')"
        >禁用</el-button>
        <el-button
          slot="left"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="danger"
          @click="giftRecordShowQuery"
          :disabled="crud.selections.length !==1"
        >赠送记录</el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          :disabled="crud.selections.length < 1"
          @click="addSalesOrder()"
        >
          生成订单
        </el-button>
      </crudOperation>
      <!--表单组件-->
      <el-dialog
        title="赠送记录"
        :visible.sync="giftRecordShow"
        width="50%"
      >
        <el-table ref="table1"
                  stripe
                  border
                  :data="giftRecordList"
                  size="small"
                  style="width: 100%;"
                  height="500"
                  :show-summary="true"
        >
          <el-table-column  type="selection" width="60"/>
          <el-table-column  type="index" width="60" label="序号"/>
          <el-table-column  prop="busDate" label="业务日期"/>
          <el-table-column  prop="customerCode" label="客户编码"/>
          <el-table-column  prop="customerName" label="客户名称"/>
          <el-table-column  prop="orderCode" label="单据编号">
            <template slot-scope="{row}">
              <div style="color: blue;cursor: pointer" @click="jumpSales(row.orderId)">{{ row.orderCode }}</div>
            </template>
          </el-table-column>
          <el-table-column  prop="goodsCount" label="数量"/>
          <el-table-column  prop="goodsCount" label="辅数量">
            <template slot-scope="{row}">
              {{ `${row.boxNum}${row.boxUnitName}${row.mainNum}${row.mainUnitName}` }}
            </template>
          </el-table-column>
          <el-table-column  prop="remark" label="备注"/>
        </el-table>

        <el-pagination
          :current-page="giftRecordQuery.page"
          :page-size="giftRecordQuery.size"
          layout="total, prev, pager, next"
          :total="giftRecordQuery.total"
          :pager-count="5"
          @current-change="currentcurrent"
        />
      </el-dialog>
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="1024px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="商品类型" prop="goodsTagId">
                <zSelect :value.sync="form.goodsTagId" :showName="form.goodsTagName"  v-model="form.goodsTagId"  @change="changTag"   url="api/dropDown/basGoodsTagList"    style="width: 100%;"/>
<!--                <el-select-->
<!--                  v-model="form.giftType"-->
<!--                  class="filter-item"-->
<!--                  clearable-->
<!--                  placeholder="商品类型"-->
<!--                  size="small"-->
<!--                  style="width: 100%"-->
<!--                  @change="crud.toQuery"-->
<!--                >-->
<!--                  <el-option-->
<!--                    v-for="item in dict.t_sales_gift_list_gift_type"-->
<!--                    :key="item.id"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value + ''"-->
<!--                  />-->
<!--                </el-select>-->
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="来源类型">-->
<!--                <el-select-->
<!--                  v-model="form.sourceType"-->
<!--                  class="filter-item"-->
<!--                  clearable-->
<!--                  placeholder="来源类型"-->
<!--                  size="small"-->
<!--                  style="width: 100%"-->
<!--                  @change="crud.toQuery"-->
<!--                >-->
<!--                  <el-option-->
<!--                    v-for="item in dict.t_sales_gift_list_source_type"-->
<!--                    :key="item.id"-->
<!--                    :label="item.label"-->
<!--                    :value="item.value + ''"-->
<!--                  />-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
<!--            <el-col :span="12">-->
<!--              <el-form-item label="来源单据号">-->
<!--                <el-input v-model="form.sourceCode"   style="width: 100%" />-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerId">
                <zSelect :value.sync="form.customerId" @change="joinCustomer" :showName="form.customerName" url="api/dropDown/basCustomerList" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称" prop="goodsId">
                <jtg-select-plus ref="productRef"
                                 v-model="form.goodsId"
                                 @change="changeGoods"
                                 :initValue="form.goodsName"
                                 @remoteMethod="getValue($event,scope.$index)"
                                 @input="getInput($event,name,scope.$index)"
                                 url="productList"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
          <el-form-item label="生效日期" prop="effectDate">
            <el-date-picker
              v-model="form.effectDate" style="width: 100%"
              type="date"
              @change="setCutOffDate"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"/>
          </el-form-item>
            </el-col>
            <el-col :span="12">
          <el-form-item label="截止日期" prop="cutOffDate">
            <el-date-picker
              v-model="form.cutOffDate" style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"/>
          </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="箱数" prop="boxCount">
                <el-input v-model="form.boxCount" type="number"  @change="changeCount('boxCount')"   style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量" prop="goodsCount">
                <el-input v-model="form.goodsCount"  @change="changeCount('goodsCount')" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注">
                <el-input v-model="form.remark"   style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="含税单价" v-if="form.goodsTagName === '预付酒'" prop="taxPrice">
                <el-input v-model="form.taxPrice"  @change="changePrice('taxPrice')"  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="含税箱价" v-if="form.goodsTagName === '预付酒'" prop="taxBoxPrice">
                <el-input v-model="form.taxBoxPrice"  @change="changePrice('taxBoxPrice')"  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="含税金额" v-if="form.goodsTagName === '预付酒'" prop="taxPrice">
                <el-input v-model="form.taxAmount" disabled  style="width: 100%" />
              </el-form-item>
            </el-col>
            <!--            <el-col :span="12">-->
<!--              <el-form-item label="商品來源">-->
<!--                <zSelect collapseTags  :value.sync="form.goodsTagId"  :showName="form.goodsTagName"  url="api/dropDown/basGoodsTagList" style="width: 100%;"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="所属商贸公司">
                <zSelect :value.sync="form.fcustomerId"  v-model="form.fcustomerId"   :showName="form.fCustomerName"   url="api/dropDown/basCustomerList" :params="{type:2}"
                         style="width: 100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属二批">
                <zSelect :value.sync="form.sCustomerId"
                         v-model="form.sCustomerId"
                         :showName="form.sCustomerName"
                         :json="scustomerList"
                         @change="changeScustomer"
                         style="width: 100%"/>
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="赠送比例(%)">-->
<!--                <el-input-number v-model="form.giftRate"   style="width: 100%"/>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
            <el-col :span="12">
              <el-form-item label="状态">
                <el-select
                  v-model="form.status"
                  class="filter-item"
                  clearable
                  placeholder="状态"
                  size="small"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in dict.common_status"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否赠箱">
                <el-select v-model="form.isGiftPaperBox" class="edit-input" placeholder="请选择"         style="width:  100%">
                  <el-option
                    v-for="(item,index) in dict.common_yes_or_no"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                    style="width: 100%"
                  />
                </el-select>
              </el-form-item>
            </el-col>
<!--            <el-col :span="12">-->
<!--              <el-form-item label="赠品清单数量">-->
<!--                 <span>{{ (form.goodsCount||0)*(form.boxCount || 0)}}</span>-->
<!--              </el-form-item>-->
<!--            </el-col>-->
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>
      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table"  border
                height="700"
                show-summary
                @cell-dblclick="row=>crud.toEdit(row)"
                v-loading="crud.loading"
                :data="crud.data"
                size="small"
                style="width: 100%;"
                v-if="isShowTable"
                @sort-change="sortTab"
                @header-dragend="changeColWidth"
                @contextmenu.native="showMenu"
                :summary-method="sumRow"
                @row-click="crud.selectRow"
                :row-style="crud.rowClass"
                :row-class-name="crud.tableRowClassName"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60" />
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
          :sortable="item.sortable?'custom':false"
          :sort-orders="['descending', 'ascending', null]"
          sort-change="sort"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" style="margin-left: 0px">{{scope.row[`${item.prop}`]}}</span>
              <span v-if="item.type == 2" style="margin-left: 0px">{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-if="item.type == 3" style="margin-left: 0px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
            </template>
          </template>
        </el-table-column>
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate" label="业务日期">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.busDate) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('giftType')" prop="giftType" label="赠品类型" >-->
<!--          <template slot-scope="scope">-->
<!--            <el-tag>{{ dictName(dict.t_sales_gift_list_gift_type,scope.row.giftType)  }}</el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsTagName')" prop="goodsTagName" label="商品类型" >-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerCode')" prop="customerCode" label="客户编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName" label="客户名称" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCode')" prop="goodsCode" label="商品编码" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsName')" prop="goodsName" label="商品名称" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('goodsCount')" prop="goodsCount" label="数量" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('boxCount')" prop="boxCount" label="箱数" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('scustomerName')" prop="boxCount" label="所属二批" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('fcustomerName')" prop="fcustomerName" label="所属商贸公司" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('giftGoodsCount')" prop="giftGoodsCount" label="已赠送数量" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('giftBoxCount')" prop="giftBoxCount" label="已赠送箱数" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('unGiftGoodsCount')" prop="unGiftGoodsCount" label="未赠数量" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('unGiftBoxCount')" prop="unGiftBoxCount" label="未赠箱数" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('giftRate')" prop="giftRate" label="赠送比例(%)" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('effectDate')" prop="effectDate" label="生效日期">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.effectDate) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cutOffDate')" prop="cutOffDate" label="截止日期">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.cutOffDate) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('seq')" prop="seq" label="排序" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('status')" prop="status" label="状态" >-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ dictName(dict.common_status,scope.row.status) }}</span>-->
<!--          </template>-->

<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createUserName')" prop="createUserName" label="添加人" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('createTime')" prop="createTime" label="添加时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.createTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateUserName')" prop="updateUserName" label="修改人" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('updateTime')" prop="updateTime" label="修改时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.updateTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('auditUserName')" prop="auditUserName" label="审核人" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('auditTime')" prop="auditTime" label="审核时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.auditTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelUserName')" prop="cancelUserName" label="核销人" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelDate')" prop="cancelDate" label="核销时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.cancelDate) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('closeUserName')" prop="closeUserName" label="关闭人" />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('closeTime')" prop="closeTime" label="关闭时间">-->
<!--          <template slot-scope="scope">-->
<!--            <span>{{ parseTime(scope.row.closeTime) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','salesGiftList:edit','salesGiftList:del']" label="操作" width="150px" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <udOperation-->
<!--              :data="scope.row"-->
<!--              :permission="permission"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudSalesGiftList from '@/api/erp/salesGiftList'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jtgSelectPlus from '@/components/select/JtgSelectPlus'
import {getDepts} from "@/api/system/dept";
import TreeSelect from '@riophae/vue-treeselect'
import { publicListKey } from "@/utils/key";
import {getHeaderProperties} from "@/api/erp/headerProperties";
import {tablemixins} from "@/mixins/tablemixins";
import  jTableColumnConfig  from "@/components/jTableColumnConfig/jTableColumnConfig";
import { giftRecord,addSalesOrder } from '../../../api/erp/salesGiftList'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '赠品清单', url: 'api/salesGiftList', sort: 'id,desc', crudMethod: { ...crudSalesGiftList },
  optShow: {
    add: true,
    edit: true,
    del: true,
    download: true,
    leadingIn: true,
    enable: false,
    disable: false
  },
})
const defaultForm = { id: null, busDate: null, giftType: null, sourceType: null, sourceId: null, sourceCode: null, customerId: null, customerCode: null, customerName: null, isContact: null, customerAreaId: null, customerAreaCode: null, customerAreaName: null, customerTypeId: null, customerTypeCode: null, customerTypeName: null, deptId: null, deptCode: null, deptName: null, userId: null, userCode: null, userName: null, goodsId: null, goodsCode: null, goodsName: null, barcode: null, boxBarcode: null, helpSign: null, model: null, goodsBrandId: null, goodsBrandCode: null, goodsBrandName: null, goodsTypeId: null, goodsTypeCode: null, goodsTypeName: null, goodsTagId: null, goodsTagCode: null, goodsTagName: null, taxId: null, taxCode: null, taxName: null, taxRate: null, boxUnitId: null, boxUnitCode: null, boxUnitName: null, boxUnitCount: null, boxNum: null, mainUnitId: null, mainUnitCode: null, mainUnitName: null, mainUnitCount: null, mainNum: null, goodsCount: 0, boxCount: 0, giftRate: null, effectDate: null, cutOffDate: null, seq: null, status: null, remark: null, createUserId: null, createUserCode: null, createUserName: null, createTime: null, updateUserId: null, updateUserCode: null, updateUserName: null, updateTime: null, isGiftPaperBox: 0, sCustomerId: null, sCustomerName: null, taxPrice: null,taxBoxPrice: null, taxAmount: null }
export default {
  name: 'salesGiftList',
  components: { pagination, crudOperation, rrOperation, udOperation,jtgSelectPlus ,jTableColumnConfig,TreeSelect},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(),publicListKey,tablemixins],
  dicts: ['common_status','t_sales_gift_list_gift_type','t_sales_gift_list_source_type','t_bas_goods_source_type','common_yes_or_no'],
  data() {
    return {
      isShow: true,
      giftRecordShow: false,
      giftRecordList: [],
      deptList: [],
      permission: {
        add: ['admin', 'salesGiftList:add'],
        edit: ['admin', 'salesGiftList:edit'],
        del: ['admin', 'salesGiftList:del'],
        import: ['admin', 'salesGiftList:import'],
        export: ['admin', 'salesGiftList:export'],
        copy: ['admin', 'salesGiftList:copy'],
        upload: ['admin', 'salesGiftList:upload'],
        download: ['admin', 'salesGiftList:download'],
        enable: ['admin', 'salesGiftList:enable'],
        disable: ['admin', 'salesGiftList:disable'],
      },
      giftRecordQuery:{
        page: 1,
        size: 10,
        total: 0,
      },
      boxUnitCount:0,
      scustomerList:'',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      rules: {
        goodsId: [
          { required: true, message: '商品id不能为空', trigger: 'blur' },
        ],
        goodsTagId: [
          { required: true, message: '商品类型不能为空', trigger: 'blur' },
        ],
        customerId: [
          { required: true, message: '客户不能为空', trigger: 'blur' },
        ],
        effectDate: [
          { required: true, message: '生效日期不能为空', trigger: 'blur' },
        ],
        cutOffDate: [
          { required: true, message: '截至日期不能为空', trigger: 'blur' },
        ],
        goodsCount: [
          { required: true, message: '数量不能为空', trigger: 'blur' },
        ],
        boxCount: [
          { required: true, message: '箱数不能为空', trigger: 'blur' },
        ],
        taxPrice: [
          { required: true, message: '含税单价不能为空', trigger: 'blur' },
        ],
        taxBoxPrice: [
          { required: true, message: '含税箱价不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  created(){
    this.getDepts()
  },
  methods: {
    resetQuery(){
      console.log('resetQuery')
      this.isShow = false
      this.query.fCustomerIds = null
      this.query.sCustomerIds = null
      this.crud.resetQuery()
      setTimeout(()=>{
        this.isShow = true
      },1)
    },
    getValue(e){
      this.query.startTime =this.query.dataExtent[0]
      this.query.endTime =this.query.dataExtent[1]
    },
    setCutOffDate(val){
      const cutOffDate = (Number(val.slice(0,4)) + 100)+val.slice(4,val.length) || null
      this.$set(this.crud.form,'cutOffDate',cutOffDate)
    },
    changePrice(type){
      if (type === 'taxPrice'){
        const boxPrice = Number(this.form.boxUnitCount) * Number(this.form.taxPrice)
        this.$set(this.form,'taxBoxPrice',boxPrice)
      }else if(type === 'taxBoxPrice'){
        const price = (Number(this.form.taxBoxPrice) / Number(this.form.boxUnitCount)).toFixed(6)
        this.$set(this.form,'taxPrice',price)
      }
      this.setTaxAmount()
    },
    setTaxAmount(){
      this.$set(this.form,'taxAmount',Number(this.form.goodsCount) * Number(this.form.taxPrice) || 0)
    },
    changeScustomer(e){
      this.form.scustomerId = this.form.sCustomerId
    },
    getValuePlus(e,i){
      console.log('this.crud.data',this.crud.data )
      this.crud.data[i].goodsName = e
      // let temp = this.crud.data[2]
      // this.crud.data[3] = temp
      this.crud.data.map(item => {
        // item.existId = 0
        // item.existNum = 0
        if(item.existBox === null){
          item.existBox = 0
        }
        if(item.occupyBox === null){
          item.occupyBox = 0
        }
        // item.occupyNum = 0
        // item.paperNum = 0
        // item.profitLossNum = 0

        // item.profitLossBox = 0
        // item.stockTaxPrice = 0
        // item.storehouseId = 0
        // item.storehouseName = 0
      })
    },
    getInput(e,name,i){
      console.log(',data.goodsName',e,name,i)
      if(this.crud.data){
        if(e){
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= e
        }else{
          this.crud.data[i].goodsName = ''
          this.crud.data[i].goodsId= null
        }
      }},
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeSubmit]() {
      this.form.fCustomerId = this.form.fcustomerId
      this.form.scustomerId = this.form.sCustomerId
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    getSelectSum(type){
      let i  = 0
      this.crud.selections.forEach(item=>{
        i+=item[type]
      })
      return i
    },
    sumRow({columns, data}) {
      const sums = []
      for (let i in columns) {
        const prop = this.crud.summary[columns[i].property]
        if (prop){
          sums[i] = <p>{this.getSelectSum(columns[i].property)}<hr />{prop}</p>
        }else {
          sums[i] = ''
        }
      }
      sums[0] =
        <p>
          选中合计
          <hr />
          合计
        </p>
      return sums
    },
    changeGoods(data,name){
      this.form.boxUnitCount = data.boxUnitCount
    },
    giftRecordShowQuery(){
      this.giftRecordShow = true
      this.giftRecordQuery.page = 1
      this.getGiftRecordList()
    },
    joinCustomer(val){
      if (val.scustomerCode){
        const scustomer =
        val.scustomerList.map(item=>{return {
          id:item.scustomerId,name:item.scustomerName
        }})
        this.scustomerList = JSON.stringify(scustomer)
        this.form.sCustomerId = val.scustomerList[0].scustomerId
        this.form.sCustomerName = val.scustomerList[0].scustomerName
      }else {
        this.scustomerList = '[]'
        this.form.sCustomerId = ''
        this.form.sCustomerName = ''
      }
    },
    changTag(e){
      this.form.goodsTagName = e.name
    },
    getGiftRecordList(){
      const id = this.$refs.table.selection[0].id
      crudSalesGiftList.giftRecord({id,...this.giftRecordQuery}).then(res=>{
        this.giftRecordList  = res.data.content
        this.giftRecordQuery.total = res.data.totalElements
      })
    },
    jumpSales(id){
      this.$router.push({path:'/sale/salesorderDetail/'+id})
    },
    currentcurrent(val){
      console.log(val)
      this.giftRecordQuery.page = val
      this.getGiftRecordList()
    },
    changeCount(type){
      if (type === 'goodsCount'){
        const boxCount = (Number(this.form.goodsCount)|| 0) / Number(this.form.boxUnitCount || 0)
        // this.form.boxCount = boxCount
        this.$set(this.form,'boxCount',boxCount.toFixed(2))
      }else {
        const goodsCount = ((Number(this.form.boxCount)|| 0) * Number(this.form.boxUnitCount || 0)).toFixed(2)

        // this.form.goodsCount = goodsCount
        this.$set(this.form,'goodsCount',goodsCount)
      }
      this.form.unGiftGoodsCount =  Number(this.form.goodsCount) -  (Number(this.form.giftGoodsCount)|| 0)
      this.form.unGiftBoxCount = Number(this.form.boxCount) -  (Number(this.form.giftBoxCount)|| 0)
      this.setTaxAmount()
    },
    getDepts(){//部门
      getDepts({status: 1}).then(res => {
        this.deptList = res
      })
    },
    getNoStr(val,type,prop){
      let str = ''
      val.forEach(item=>{
        const itemNode = this.getTreeName1(this[type],item)
        str = this.getNode(itemNode,str)
      })
      this.query[prop] = str
    },
    getTreeName1(treeList,id){
      let _this=this
      for (let i = 0; i < treeList.length; i++) {
        let treeItem=treeList[i]
        if(treeItem.id===id){
          return treeItem
        }else{
          if(treeItem.children && treeItem.children.length>0){
            let res=_this.getTreeName(treeItem.children,id)
            if(res){
              return res
            }
          }
        }
      }
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=node.id+ ','
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    addSalesOrder(){
      const ids = []
      this.crud.selections.forEach(o => {
        ids.push(o.id)
      })
      addSalesOrder(ids).then(res=>{
        if (res.status === 200) {
          this.$message.success(res.msg)
          this.crud.refresh()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
  }
}
</script>

<style scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
